//
//  ByShopProductDetailSkuVC.m
//  hutouben_ios
//
//  Created by pro on 16/11/30.
//  Copyright © 2016年 mc. All rights reserved.
//

#import "ByShopProductDetailSkuVC.h"

// view
#import "ByProductSkuCollectionView.h"
#import "ByProductSkuSelectView.h"
// model
#import "SkuModel.h"
#import "SkuIdModel.h"
#import "SkuNameModel.h"
// handle
#import "ProductInfoHandle.h"



@interface ByShopProductDetailSkuVC () <ByProductSkuCollectionViewDataSource>

@property (nonatomic, strong) ByProductSkuCollectionView *collect;

@property (nonatomic, strong) NSArray<SkuModel *>       *skuAry;
@property (nonatomic, strong) NSArray<SkuIdModel *>     *skuIdAry;
@property (nonatomic, strong) NSArray<SkuNameModel *>   *skuNameAry;

@property (nonatomic, copy) NSArray *items1;
@property (nonatomic, copy) NSArray *items2;

@end

@implementation ByShopProductDetailSkuVC
{
    NSMutableArray  *_skuSelectModelArray; // 用于布局单元格（有几组规格就有几个元素）
    NSMutableArray  *_skuSelectIdArray; // 用于获得选中的skuId（1：1），拼接数组
    SkuModel        *_selectedModel; // 选中的某种规格的商品model，用于添加购物车，或立即购买
    NSInteger       _selectCount; // 选中的数量
}

// 数据设置
// 规格内容数组
- (void)setSkuNameAry:(NSArray<SkuNameModel *> *)skuNameAry {
    _skuNameAry = skuNameAry;
    
    _skuSelectModelArray = [[NSMutableArray alloc] init];
    for (int i = 0;  i < _skuNameAry.count; i ++) {
        
        SkuCellSelectModel *model = [[SkuCellSelectModel alloc] init];
        SkuNameModel *skuNameModel = _skuNameAry[i];
        model.rowCount = skuNameModel.vidAry_des.count;
        model.currentSection = i;
        [_skuSelectModelArray addObject:model];
    }
        
}
// 规格id数组
- (void)setSkuIdAry:(NSArray<SkuIdModel *> *)skuIdAry {
    _skuIdAry = skuIdAry;
    
    _skuSelectIdArray = [[NSMutableArray alloc] init];
    
    for (int i = 0;  i < _skuIdAry.count; i ++) {
        
        NSString *keyId = [ProductInfoHandle getDefaultNoIDString];
        [_skuSelectIdArray addObject:keyId];
    }
    
}
// 规格列表数组
- (void)setSkuAry:(NSArray<SkuModel *> *)skuAry {
    _skuAry = skuAry;
    
    if (_skuAry.count == 1) { // 表示统一规格
        _selectedModel = [_skuAry firstObject];
    }
}
// 商品详情
- (void)setDetailModel:(ByNetProductDetailModel *)detailModel {
    _detailModel = detailModel;
    
    self.skuNameAry = _detailModel.skuNameAry;
    self.skuIdAry   = _detailModel.skuIdAry;
    self.skuAry     = _detailModel.skuAry;   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _selectCount = 1;

    [self setupUI];
}


- (void)setupUI {
    
    self.collect = [[ByProductSkuCollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, SCREEN_HEIGHT - 200 - 40)];
    self.collect.dataSource = self;
    [self.view addSubview:self.collect];
    
    UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
    okButton.frame = CGRectMake(0, 0, self.view.width, 40);
    okButton.backgroundColor = HTB_THEME_COLOR;
    [okButton setTitle:@"确认加入" forState:UIControlStateNormal];
    [okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [okButton addTarget:self action:@selector(okAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:okButton];
    okButton.bottom = SCREEN_HEIGHT - 200;
    
    NSLog(@"%@", NSStringFromCGRect(self.view.bounds));
}

#pragma mark - dataSource 
- (NSInteger)numOfSections:(ByProductSkuCollectionView *)collectionView {
    
    return 2;
}

- (NSInteger)numOfItems:(ByProductSkuCollectionView *)collectionView inSection:(NSInteger)section {
    
    SkuNameModel *model = _skuNameAry[section];
    return model.vidAry_des.count;
    
    return 0;
}

- (NSString *)collectionView:(ByProductSkuCollectionView *)collectionView titleInSection:(NSInteger)section {
    
    SkuNameModel *model = _skuNameAry[section];
    return model.sid_des;
}

- (void)collectionView:(ByProductSkuCollectionView *)collectionView didModifyCount:(NSInteger (^)())modify {
    
    _selectCount = modify();
}

- (UIView *)collectionView:(ByProductSkuCollectionView *)collectionView viewAtIndexPath:(NSIndexPath *)indexPath {
    
    ByProductSkuSelectView *cell = [[ByProductSkuSelectView alloc] init];
    CGSize size = [self collectionView:collectionView sizeForviewAtIndexPath:indexPath];
    cell.labelSort.frame = CGRectMake(0, 0, size.width, size.height);
    
    // 1.数据展示
    SkuNameModel *model = _skuNameAry[indexPath.section];
    NSString *text = model.vidAry_des[indexPath.row];
    cell.labelSort.text = text;
    
    // 2.collection颜色变化
    // 选择中模型
    SkuCellSelectModel *selectModel = _skuSelectModelArray[indexPath.section];
    cell.tag = indexPath.row;
    cell.userInteractionEnabled = YES;
    
    // 获得该row的单元格是否可点击
    BOOL isAble = [selectModel.isableTouchCollectArray[indexPath.row] boolValue];
    if (!isAble) {
        cell.userInteractionEnabled = NO; // 不可点击的单元格做处理
    }
    
    // 3.cell处理（单元格背景颜色和字体颜色变化）
    [cell showSelectCollectionRow:selectModel];
    
    return cell;
}
- (CGSize)collectionView:(ByProductSkuCollectionView *)collectionView sizeForviewAtIndexPath:(NSIndexPath *)indexPath {
    
    SkuNameModel *model = _skuNameAry[indexPath.section];

    return CGSizeMake([model.vidAry_des[indexPath.item] getSizeOfString:14].width + 20, 30);
}
- (void)collectionView:(ByProductSkuCollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // _skuSelectModelArray 有多少分区就有多少selectModel的对象，对的对应组的该对方，判断当前点击是否可点
    SkuCellSelectModel *selectModel = _skuSelectModelArray[indexPath.section];
    BOOL isAble = [selectModel.isableTouchCollectArray[indexPath.row] boolValue];
    
    // 不能点击
    if (!isAble) {
        return;
    }
    // 能点击
    else {
        // 初始化 _skuSelectModelArray ，使 bool为YES，然后再判断赋值
        for (NSInteger i = 0  ; i < _skuSelectModelArray.count; i ++) {
            SkuCellSelectModel *selectModel = [_skuSelectModelArray objectAtIndex:i];
            
            [selectModel changeStateOfTouchCollectArray:YES];
        }
    }
    
    // **** 记录当前collection的选择状态（SkuCellSelectModel），为后面刷新collecView时规格状态改变铺路  ***
    NSString *keyID = nil;
    if (selectModel.selectRow == indexPath.row) {
        selectModel.selectRow = -1;
        selectModel.selectSection = -1;
        NSLog(@"同一个单元格");
        // 默认字符串 sku_id:
        keyID = [ProductInfoHandle getDefaultNoIDString];
        
    } else {
        // 当前单元格对应ID（46：128）
        keyID = [ProductInfoHandle getCurrCollectSkuId:indexPath skuIdModel:_skuIdAry[indexPath.section]];
        NSLog(@"当前单元格的skuId:%@", keyID);
        // 刷新
        [selectModel reloadSelectRow:indexPath.row section:indexPath.section];
    }
    
    // 2.改变保存的skuKeyID
    [_skuSelectIdArray replaceObjectAtIndex:indexPath.section withObject:keyID];
    
    // 3.做判断，选择是否合法（是否可以组成完成的sku_id）--- isAble
    [ProductInfoHandle isUseableSkuIdArray:_skuSelectIdArray complete:^(BOOL isable) {
        
        if (isable) {  // 如果所有规格都选择了，查找选择的模型
            
            // 去掉当前选择的组的另外的组
            NSArray *selecKeyValuetArray = [ProductInfoHandle getSelectSkuIDList:_skuSelectIdArray except:indexPath.section];
            
            // 预测当前点击的组中可点击的单元格
            [self getOnlyOneSkuNotSelectCollectIndex:selecKeyValuetArray index:indexPath.section];
            
            // 根据规格ID找到对应商品
            SkuModel *model = [self getSelectSkuModel];
            if (model != nil ) {  //展示商品详情信息
                
                // 找到了正确的商品
                _selectedModel = model;
            }
            // 如果没有找到，或者库存为0，都要把当前sku_id,改掉
            if (model == nil || [model.quantity boolValue] == 0) {
                
                [_skuSelectIdArray replaceObjectAtIndex:indexPath.section withObject:[ProductInfoHandle getDefaultNoIDString]];
                
                SkuCellSelectModel *selectModel = _skuSelectModelArray[indexPath.section];
                [selectModel reloadSelectRow:-1 section:indexPath.section];
                
                // 该商品库存为0
                _selectedModel = nil;
            }
        }
        //返回还没有被选择的分区下标:"0" "1",
    } noSelectAry:^(NSArray *notSeletSectionArray) {
        
        // 如果只有一个分区没有被选中
        if (notSeletSectionArray.count == 1) {
            
            // selectedSkuIdAry:是除了未赋值的所有skuId的数组
            // 而_skuSelectIdArray是包含了未赋值的所有的skuId的数组
            NSArray *selectedSkuIdAry = [ProductInfoHandle getSelectedSkuIdAry:_skuSelectIdArray];
            
            // 获得没被选择的组的索引（section）
            NSInteger section = [[notSeletSectionArray lastObject] integerValue];
            
            [self getOnlyOneSkuNotSelectCollectIndex:selectedSkuIdAry index:section];
        }
                
        // 没有选择全部的规格
        _selectedModel = nil;
    }];
    
    // TODO: 选中的skuid数组（1：3，2：4），可以拼接成sku_id（1：3；2：4；）然后可以获得详细的商品
    NSLog(@"****keyIdAry*****:%@ \n选中的商品sku_id:%@", _skuSelectIdArray, _selectedModel.sku_id);
    
    //5 ,刷新
    [_collect reloadData];

}


#pragma mark - 点击事件
- (void)okAction {
    
    if (!_selectedModel) {
        [ByCoreToolAlert showFailureWithText:@"请选择规格"];
        return;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    self.backAction(_selectedModel, _selectCount);
}

#pragma mark - 其他方法（代码太多，写成代码块方法）
// 根据选中的id字符串 找到对应的商品
- (SkuModel *)getSelectSkuModel {
    
    NSString *fullSkuId = [ProductInfoHandle getFullSkuId:_skuSelectIdArray];
    //根据sku_id 找规格模型
    SkuModel *model = [ProductInfoHandle findSkuModelInSkuAry:_detailModel.skuAry fullSkuId:fullSkuId];
    
    return model;
}
- (void)getOnlyOneSkuNotSelectCollectIndex:(NSArray *)selecKeyValuetAry index:(NSInteger )section{
    
    /**
     没有选择的分区的处理
     找到预测分区中不可点击的row并记录下来
     */
    [ProductInfoHandle forecastSkuIdIsable:_detailModel selectedSkuIdAry:selecKeyValuetAry section:section disAbleBlock:^(NSArray *disTouchSkuIDArray) {
        
        // 获得该组对应的规格选择模型（用于重置可选数组）
        SkuCellSelectModel *selectModel = [_skuSelectModelArray objectAtIndex:section];
        
        // 如果不可选数组为空，则该组的单元格全部可选
        if (disTouchSkuIDArray.count == 0 || disTouchSkuIDArray == nil) {
            [selectModel changeStateOfTouchCollectArray:YES];
        } else {
            SkuIdModel *model = _skuIdAry[section];
            // 如果不可选数组中有（47:129），而该组的整个规格有（47:129 ; 47:130），则找出索引为0并设置不可选
            for (NSString *key in disTouchSkuIDArray) {
                NSInteger index = [model getKeyValueIndex:key];
                [selectModel.isableTouchCollectArray replaceObjectAtIndex:index withObject:@NO];
            }
        }
    }];
}


@end
